package com.shopping.mall.base.search.util;

import com.alibaba.fastjson.JSON;
import org.apache.poi.ss.formula.functions.T;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class SearchUtils {
    @Autowired
    private RestHighLevelClient restHighLevelClient;



    public void addDocument(String index,String id,Object data) throws IOException {
        IndexRequest request = new IndexRequest(index);
        request.id(id);
        request.source(JSON.toJSON(data), XContentType.JSON);
        IndexResponse response=restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    public Object getDocument(String index,String id) throws IOException {
        GetRequest request = new GetRequest(index);
        request.id(id);
        GetResponse response=restHighLevelClient.get(request,RequestOptions.DEFAULT);
        if(response.isExists()){
            return JSON.parse(response.getSourceAsBytes());
        }
        return null;
    }

    public void updateJSON(){

    }
}
